# -*- encoding: utf-8 -*-
"""
    Created by Rachel on 2025/03/06
"""
import os
import pkgutil

from sqlalchemy import Column, Integer

from applications.ext.init_sqlalchemy import db


class BaseMixin(db.Model):
    __abstract__ = True

    id = Column(Integer, primary_key=True, autoincrement=True, index=True)

    def write(self, commit=False, **kwargs):
        """
        更新数据
        :param commit: 是否提交
        :return:
        """
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)
        db.session.commit() if commit else db.session.flush()
        return self

    def delete(self, commit=False):
        """
        删除记录
        :param commit: 是否提交
        :return:
        """
        db.session.delete(self)
        if commit:
            db.session.commit()

    @classmethod
    def create(cls, commit=False, **kwargs):
        """
        创建方法
        :param commit: 是否提交
        :return:
        """
        obj = cls(**kwargs)
        db.session.add(obj)
        db.session.commit() if commit else db.session.flush()
        return obj

    @classmethod
    def multi_create(cls, data):
        db.session.bulk_insert_mappings(cls, data)


class ModelRegister:
    """
    使用方式
        self.models['模型名'].query.filter().all()
        or
        db.session.query(self.models["模型名"]).filter().all()
    """

    def __init__(self, app):
        self.app = app
        self.app.models = self.model
        print(self.app.models)

    @property
    def model(self):
        return {mapper.class_.__tablename__: mapper.class_ for mapper in db.Model.registry.mappers}
